<template>
  <div class="overview-design-container">
    <!-- 背景装饰 -->
    <div class="bg-decoration">
      <div class="floating-orb orb-1"></div>
      <div class="floating-orb orb-2"></div>
      <div class="floating-orb orb-3"></div>
    </div>

    <div class="content-area">
      <div class="content-header">
        <div class="title-container">
          <h1 class="main-title">概要设计生成</h1>
          <p class="subtitle">基于COSMIC数据智能生成概要设计文档</p>
        </div>
      </div>

      <div class="form-wrapper">
        <n-form
          ref="formRef"
          :model="formModel"
          :rules="formRules"
          label-placement="top"
          size="medium"
        >
          <div class="form-grid">
            <!-- COSMIC文件导入区域 -->
            <div class="upload-section">
              <div class="upload-header">
                <h3 class="section-title">导入COSMIC文件</h3>
                <p class="section-desc">请选择包含COSMIC数据的Excel文件</p>
              </div>
              
              <div class="upload-area" @click="uploadFile" :class="{ 'has-file': uploadedFile }">
                <input 
                  type="file" 
                  ref="fileInput" 
                  style="display: none" 
                  @change="handleFileChange"
                  accept=".xlsx,.xls"
                />
                
                <div v-if="!uploadedFile" class="upload-placeholder">
                  <div class="upload-icon">📊</div>
                  <div class="upload-text">
                    <p class="upload-title">点击上传COSMIC文件</p>
                    <p class="upload-subtitle">支持 .xlsx, .xls 格式</p>
                  </div>
                </div>
                
                <div v-else class="uploaded-file">
                  <div class="file-icon">✅</div>
                  <div class="file-info">
                    <p class="file-name">{{ uploadedFile.name }}</p>
                    <p class="file-size">{{ formatFileSize(uploadedFile.size) }}</p>
                  </div>
                  <n-button 
                    type="error" 
                    size="small" 
                    @click.stop="removeFile"
                    class="remove-btn"
                  >
                    移除
                  </n-button>
                </div>
              </div>
            </div>

            <!-- 基本信息表单 -->
            <div class="info-section">
              <div class="info-header">
                <h3 class="section-title">基本信息</h3>
                <p class="section-desc">请填写概要设计文档的基本信息</p>
              </div>

              <div class="form-fields">
                <n-form-item label="需求名称" path="requirementName" class="form-item">
                  <n-input
                    v-model:value="formModel.requirementName"
                    placeholder="请输入需求名称"
                    clearable
                    class="modern-input"
                  />
                </n-form-item>

                <n-form-item label="作者" path="author" class="form-item">
                  <n-input
                    v-model:value="formModel.author"
                    placeholder="请输入作者姓名"
                    clearable
                    class="modern-input"
                  />
                </n-form-item>

                <n-form-item label="编写时间" path="writeTime" class="form-item">
                  <n-input
                    v-model:value="formModel.writeTime"
                    placeholder="yyyy年MM月dd日"
                    clearable
                    class="modern-input"
                  />
                </n-form-item>
              </div>
            </div>
          </div>

          <!-- COSMIC数据预览 -->
          <div v-if="cosmicData.length > 0" class="data-preview-section">
            <div class="section-header">
              <h3 class="section-title">COSMIC数据预览</h3>
              <span class="data-count">共 {{ cosmicData.length }} 条数据</span>
            </div>
            
            <div class="data-table-wrapper">
              <n-data-table 
                :columns="tableColumns" 
                :data="cosmicData" 
                :single-line="false"
                :max-height="400"
                class="cosmic-table"
              />
            </div>
          </div>

          <!-- 生成按钮 -->
          <div class="generate-section">
            <n-button 
              type="primary" 
              size="large"
              @click="generateOverviewDesign"
              :loading="generating"
              :disabled="!canGenerate"
              class="generate-btn"
            >
              <template #icon>
                <div class="btn-icon">🚀</div>
              </template>
              {{ generating ? '正在生成概要设计...' : '生成概要设计文档' }}
            </n-button>
          </div>
        </n-form>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { invoke } from '@tauri-apps/api/core';

  const message = useMessage();

  // 状态管理
  const fileInput = ref(null);
  const formRef = ref(null);
  const uploadedFile = ref(null);
  const cosmicData = ref([]);
  const generating = ref(false);

  // 表单数据
  const formModel = reactive({
    requirementName: '',
    author: '',
    writeTime: ''
  });

  // 表单验证规则
  const formRules = {
    requirementName: [
      { required: true, message: '请输入需求名称', trigger: 'blur' }
    ],
    author: [
      { required: true, message: '请输入作者姓名', trigger: 'blur' }
    ],
    writeTime: [
      { required: true, message: '请输入编写时间', trigger: 'blur' }
    ]
  };

  // 表格列定义
  const tableColumns = [
    {
      title: '功能用户需求',
      key: 'functional_requirement',
      width: 200,
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '触发事件',
      key: 'trigger_event',
      width: 150,
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '功能过程',
      key: 'functional_process',
      width: 200,
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '子过程描述',
      key: 'subprocess_description',
      width: 250,
      ellipsis: {
        tooltip: true
      }
    },
    {
      title: '数据移动类型',
      key: 'data_movement_type',
      width: 120
    },
    {
      title: '数据组',
      key: 'data_group',
      width: 100
    },
    {
      title: '数据属性',
      key: 'data_attributes',
      width: 100
    }
  ];

  // 计算属性
  const canGenerate = computed(() => {
    return uploadedFile.value && 
           formModel.requirementName.trim() && 
           formModel.author.trim() && 
           formModel.writeTime.trim();
  });

  // 初始化默认时间
  const initDefaultTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    formModel.writeTime = `${year}年${month}月${day}日`;
  };

  // 组件挂载时初始化
  onMounted(() => {
    initDefaultTime();
  });

  // 文件上传
  const uploadFile = () => {
    fileInput.value.click();
  };

  // 处理文件变化
  const handleFileChange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
      uploadedFile.value = file;
      
      // 读取文件并上传到后端
      const fileData = await readFileAsBase64(file);
      const uploadResult = await invoke('upload_file', {
        fileName: file.name,
        fileData: fileData
      });

      const parsedResult = JSON.parse(uploadResult);
      
      if (parsedResult.code === 200) {
        message.success('文件上传成功');
        
        // 解析Excel文件获取COSMIC数据
        const parseResult = await invoke('parse_excel', {
          filePath: parsedResult.file_path
        });
        
        cosmicData.value = parseResult;
        message.success(`成功解析 ${parseResult.length} 条COSMIC数据`);
        
      } else {
        message.error('文件上传失败: ' + parsedResult.msg);
        uploadedFile.value = null;
      }
    } catch (error) {
      console.error('文件处理失败:', error);
      message.error('文件处理失败: ' + error);
      uploadedFile.value = null;
    }
  };

  // 移除文件
  const removeFile = () => {
    uploadedFile.value = null;
    cosmicData.value = [];
    fileInput.value.value = '';
    message.info('已移除文件');
  };

  // 读取文件为Base64
  const readFileAsBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result.split(',')[1]);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 生成概要设计
  const generateOverviewDesign = async () => {
    // 表单验证
    const valid = await new Promise((resolve) => {
      formRef.value?.validate((errors) => {
        resolve(!errors);
      });
    });

    if (!valid) {
      message.warning('请完善表单信息');
      return;
    }

    if (!uploadedFile.value) {
      message.warning('请先上传COSMIC文件');
      return;
    }

    if (cosmicData.value.length === 0) {
      message.warning('没有可用的COSMIC数据');
      return;
    }

    generating.value = true;
    try {
      // 首先上传文件并获取文件路径
      const fileData = await readFileAsBase64(uploadedFile.value);
      const uploadResult = await invoke('upload_file', {
        fileName: uploadedFile.value.name,
        fileData: fileData
      });

      const parsedUploadResult = JSON.parse(uploadResult);
      
      if (parsedUploadResult.code !== 200) {
        message.error('文件上传失败: ' + parsedUploadResult.msg);
        return;
      }

      // 调用后端生成概要设计
      const result = await invoke('generate_overview_design', {
        request: {
          cosmic_file_path: parsedUploadResult.file_path,
          requirement_name: formModel.requirementName,
          author: formModel.author,
          writing_time: formModel.writeTime,
          output_path: ''  // 让后端自动生成输出路径
        }
      });

      if (result.success) {
        message.success('概要设计文档生成成功！');
        
        console.log('=== 前端收到的结果 ===');
        console.log('result:', result);
        console.log('result.output_path:', result.output_path);
        console.log('typeof result.output_path:', typeof result.output_path);
        
        // 如果有输出路径，可以打开文件夹
        if (result.output_path) {
          try {
            console.log('=== 开始调用 open_folder ===');
                console.log('调用参数:', result.output_path);
                await invoke('open_folder', { folderPath: result.output_path });
                console.log('=== open_folder 调用成功 ===');
          } catch (error) {
            console.error('=== open_folder 调用失败 ===');
            console.error('打开文件夹失败:', error);
            message.warning('文件生成成功，但无法自动打开文件夹');
          }
        } else {
          console.log('=== 没有输出路径，跳过文件打开 ===');
        }
      } else {
        message.error('生成失败: ' + result.message);
      }
    } catch (error) {
      console.error('生成概要设计失败:', error);
      message.error('生成失败: ' + error);
    } finally {
      generating.value = false;
    }
  };
</script>

<style scoped>
  .overview-design-container {
    position: relative;
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    overflow: hidden;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }

  .bg-decoration {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 1;
  }

  .floating-orb {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    animation: float 6s ease-in-out infinite;
  }

  .orb-1 {
    width: 120px;
    height: 120px;
    top: 10%;
    left: 10%;
    animation-delay: 0s;
  }

  .orb-2 {
    width: 80px;
    height: 80px;
    top: 60%;
    right: 15%;
    animation-delay: 2s;
  }

  .orb-3 {
    width: 100px;
    height: 100px;
    bottom: 20%;
    left: 20%;
    animation-delay: 4s;
  }

  @keyframes float {
    0%, 100% { transform: translateY(0px) rotate(0deg); }
    50% { transform: translateY(-20px) rotate(180deg); }
  }

  .content-area {
    position: relative;
    z-index: 2;
    padding: 40px 20px;
    max-width: 1200px;
    margin: 0 auto;
  }

  .content-header {
    text-align: center;
    margin-bottom: 40px;
  }

  .title-container {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    padding: 30px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  }

  .main-title {
    font-size: 2.5rem;
    font-weight: 700;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin: 0 0 10px 0;
  }

  .subtitle {
    font-size: 1.1rem;
    color: #64748b;
    margin: 0;
  }

  .form-wrapper {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    padding: 40px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  }

  .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 40px;
    margin-bottom: 40px;
  }

  @media (max-width: 768px) {
    .form-grid {
      grid-template-columns: 1fr;
      gap: 30px;
    }
  }

  .upload-section, .info-section {
    display: flex;
    flex-direction: column;
  }

  .upload-header, .info-header {
    margin-bottom: 20px;
  }

  .section-title {
    font-size: 1.3rem;
    font-weight: 600;
    color: #1e293b;
    margin: 0 0 8px 0;
  }

  .section-desc {
    font-size: 0.9rem;
    color: #64748b;
    margin: 0;
  }

  .upload-area {
    border: 2px dashed #d1d5db;
    border-radius: 12px;
    padding: 30px;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
    background: #f9fafb;
  }

  .upload-area:hover {
    border-color: #667eea;
    background: #f0f4ff;
  }

  .upload-area.has-file {
    border-color: #10b981;
    background: #f0fdf4;
  }

  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
  }

  .upload-icon {
    font-size: 3rem;
  }

  .upload-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #374151;
    margin: 0;
  }

  .upload-subtitle {
    font-size: 0.9rem;
    color: #6b7280;
    margin: 0;
  }

  .uploaded-file {
    display: flex;
    align-items: center;
    gap: 15px;
    text-align: left;
  }

  .file-icon {
    font-size: 2rem;
  }

  .file-info {
    flex: 1;
  }

  .file-name {
    font-weight: 600;
    color: #374151;
    margin: 0 0 4px 0;
  }

  .file-size {
    font-size: 0.9rem;
    color: #6b7280;
    margin: 0;
  }

  .form-fields {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .form-item {
    margin-bottom: 0;
  }

  .modern-input {
    border-radius: 8px;
  }

  .data-preview-section {
    margin-bottom: 40px;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .data-count {
    font-size: 0.9rem;
    color: #667eea;
    background: #f0f4ff;
    padding: 4px 12px;
    border-radius: 12px;
    font-weight: 500;
  }

  .data-table-wrapper {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .generate-section {
    text-align: center;
  }

  .generate-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 12px;
    padding: 0 40px;
    height: 50px;
    font-weight: 600;
    color: white;
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
    min-width: 200px;
    cursor: pointer;
    font-size: 1rem;
  }

  .generate-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
  }

  .generate-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
  }

  .btn-icon {
    font-size: 1.2rem;
  }

  .remove-btn {
    border-radius: 6px;
  }
</style>
